#include "App.hpp"
#include "ressource/AbstractRessource.hpp"
#include "states/MenuState.hpp"
#include "states/ProfilState.hpp"
#include "ScriptLoader.hpp"


App::App(std::string appTitle) : m_appTitle(appTitle),
	m_videoMode(GAME_DEFAULT_WINDOW_WIDTH, GAME_DEFAULT_WINDOW_HEIGHT, 32),
	m_window(),
	m_input(m_window.GetInput()),
	m_ressourceManager(),
	m_stateManager(),
	m_running(false)
{
    // Initialize and create the script Loader singleton
    ScriptLoader::GetScriptLoader(this);
}

App::~App()
{
	m_running = false;
}

void App::Run()
{
	m_running = true;

	PreInit();

	Init();

	Loop();

	CleanUp();

	m_running = false;

}

bool App::isRunning()
{
	return m_running;
}

void App::Init()
{
	m_stateManager.AddActiveState(new MenuState(this));

    ScriptLoader::GetScriptLoader()->LoadItems();

}

void App::PreInit()
{
	m_window.Create(m_videoMode, m_appTitle);

	m_window.SetFramerateLimit(60);
}

void App::ChangeResolution(int x,int y)
{
    m_window.Close();

    m_window.Create(sf::VideoMode(x,y,32), m_appTitle);
}

void App::Loop()
{
	//Loop
	if(m_stateManager.IsEmpty())
			Quit();

	while(m_running && m_window.IsOpened())
	{
		AppState* currentState = m_stateManager.ActiveState();

		sf::Event appEvent;
		while(m_window.GetEvent(appEvent))
		{
			switch(appEvent.Type)
			{
				case sf::Event::Closed:
					Quit();
				break;

				case sf::Event::GainedFocus:
					currentState->Resume();
				break;

				case sf::Event::LostFocus:
					currentState->Pause();
				break;
				default:
					currentState->HandleEvents(appEvent);
			}
		}

		currentState->Update(m_window.GetFrameTime());

		m_window.Clear();

		currentState->Draw();

		m_window.Display();

		m_stateManager.HandleCleanUp();
	}
}

void App::CleanUp()
{
	if(m_window.IsOpened())
	{
		m_window.Close();
	}
}

void App::Quit()
{
	m_running = false;
}
